package com.tengju.bff.interfaces.covercharge.service.letax;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tengju.bff.interfaces.covercharge.entity.dto.HttpClientResponse;
import com.tengju.bff.interfaces.covercharge.service.bestsign.util.HttpClientUtils;
import com.zoi7.component.core.exception.ServiceException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;

/**
 * @author cj
 * @date 2020/12/01
 * @description 乐税-客户端
 */
@Slf4j
public class LeTaxClient {

    /**
     * 乐税[post]查询服务请求
     *
     * @param
     * @param request    入参请求
     * @return 结果
     */
    public static Map sendPost(String reqUrl, Object request) {
        String requestBody = JSON.toJSONString(request);
        //获取请求地址
        log.info("乐税[post]服务请求开始,入参:{}", requestBody);
        //发送请求
        HttpClientResponse response = HttpClientUtils.postJson(reqUrl, requestBody);
        if (Objects.isNull(response)) {
            throw new ServiceException("乐税签服务请求响应结果为空");
        }
        if (!response.isOk() || !response.contentIsNotNull()) {
            JSONObject jsonObject = HttpClientUtils.responseConvert(response.getErrMsg());
            String errMsg = jsonObject.getString("errMsg");
            log.error("乐税[post]服务请求响应异常,response:{}",  response);
            throw new ServiceException(errMsg);
        }
        log.info("乐税[post]服务请求结束,response:{}",response);
        return JSON.parseObject(response.getContent(), HashMap.class);
    }

    /**
     * 乐税[get]服务请求
     *
     * @param reqUrl    请求地址
     * @return 结果
     */
    public static Map sendGet(String reqUrl) {
        //获取请求地址
        log.info("乐税[get]服务请求开始,入参:{}", reqUrl);
        //发送请求
        HttpClientResponse response = HttpClientUtils.sendHttpGet(reqUrl);
        if (Objects.isNull(response)) {
            throw new ServiceException("上上签服务请求响应结果为空");
        }
        if (!response.isOk() || !response.contentIsNotNull()) {
            JSONObject jsonObject = HttpClientUtils.responseConvert(response.getErrMsg());
            String errMsg = jsonObject.getString("error");
            log.error("乐税[post]服务请求响应异常,response:{}",  response);
            throw new ServiceException(errMsg);
        }
        log.info("乐税[post]服务请求结束,response:{}",response);
        return JSON.parseObject(response.getContent(), HashMap.class);
    }
}
